//
//  AgreementAlertView.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/28.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import WebKit
import HandyJSON

enum AgreementType: Int {
    /// 远程诊疗患者知情书
    case informedLetter = 1
    /// 免责条款
    case avoidDuty
    /// 法律及隐私权
    case lawAndPrivacy
    /// 用户注册协议
    case register
    /// 图文问诊患者同意书
    case agreementLetter
    /// 预约规则
    case reservationRule
    /// app法律及隐私权
    case appLawAndPrivacy
    /// 门诊挂号规则
    case registrationRule
    /// 患者规则
    case patientRule  = 9
}

struct AgreementViewModel: HandyJSON {
    var id: String = ""
    var type: String = ""
    var text: String = ""
    var title: String = ""
    
    static func inquiryAgreement(type: AgreementType, finished: @escaping (_ model: AgreementViewModel?, _ errorMsg: String?, _ code: HttpCode) -> Void) {
        let paras = ["type": type.rawValue]
        HttpTool.shared.request(target: ApiManager.inquiryAgreement(paras: paras), success: { (json, code) in
            let model = JSONDeserializer<AgreementViewModel>.deserializeFrom(json: json["data"].description)
            finished(model, json["message"].description, code)
        }) { errorMsg in
            finished(nil, errorMsg, .failure)
        }
    }
    static func inquiryAgreementString(type: String, finished: @escaping (_ model: AgreementViewModel?, _ errorMsg: String?, _ code: HttpCode) -> Void) {
        let paras = ["type": type]
        HttpTool.shared.request(target: ApiManager.inquiryAgreement(paras: paras), success: { (json, code) in
            let model = JSONDeserializer<AgreementViewModel>.deserializeFrom(json: json["data"].description)
            finished(model, json["message"].description, code)
        }) { errorMsg in
            finished(nil, errorMsg, .failure)
        }
    }
    
}

class AgreementAlertView: UIView {
    
    private var type = AgreementType.informedLetter
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        contentView.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.bottom.equalTo(sureBtn.snp.top).offset(-10)
        }
    }
    
    @IBOutlet private weak var maskBgView: UIView! {
        didSet {
            maskBgView.alpha = 0.0
        }
    }

    @IBOutlet private weak var contentView: UIView! {
        didSet {
            contentView.layer.cornerRadius = 16
            contentView.layer.masksToBounds = true
            contentView.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        }
    }
    
    @IBOutlet private weak var titleLabel: UILabel!
    
    private lazy var webView = WKWebView()
    
    @IBOutlet private weak var sureBtn: UIButton! {
        didSet {
            sureBtn.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
            sureBtn.setBackgroundImage(UIImage(color: .mainGray), for: .highlighted)
            sureBtn.layer.cornerRadius = sureBtn.height * 0.5
            sureBtn.layer.masksToBounds = true
        }
    }
    
    @IBAction private func sureAction(_ sender: UIButton) {
        dismiss()
    }
    
    func show(in view: UIView? = nil, type: AgreementType) {
        self.type = type
        let superview = view == nil ? mainWindow : view!
        superview.addSubview(self)
        self.frame = superview.bounds
        UIView.animate(withDuration: 0.25) {
            self.maskBgView.alpha = 1.0
            self.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
        }
        
        loadData()
    }

    func showString(in view: UIView? = nil, type: String) {

        let superview = view == nil ? mainWindow : view!
        superview.addSubview(self)
        self.frame = superview.bounds
        UIView.animate(withDuration: 0.25) {
            self.maskBgView.alpha = 1.0
            self.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
        }
        
        loadDataString(_type: type)
    }
    
    
    func dismiss() {
        UIView.animate(withDuration: 0.25, animations: {
            self.contentView.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        }) { _ in
            self.maskBgView.alpha = 0.0
            self.removeFromSuperview()
        }
    }
}

extension AgreementAlertView {
    private func loadData() {
        AgreementViewModel.inquiryAgreement(type: type) { (model, errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                guard let m = model else { return }
                self.reloadData(m)
            }
        }
    }
    
    private func loadDataString(_type : String) {
        AgreementViewModel.inquiryAgreementString(type: _type) { (model, errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                guard let m = model else { return }
                self.reloadData(m)
            }
        }
    }
    
    private func reloadData(_ model: AgreementViewModel) {
        titleLabel.text = model.title
        webView.loadHTMLString(model.text, baseURL: nil)
        
    }
}
